package de.lang.rollo.controller.managed;

import java.util.Date;
import java.util.Iterator;

import org.mongojack.JacksonDBCollection;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import com.yammer.dropwizard.lifecycle.Managed;

import de.lang.rollo.controller.logic.scheduling.RolloJob;
import de.lang.rollo.controller.model.RolloEvent;

public class SchedulerManaged implements Managed {

	private static Scheduler sched;

	public SchedulerManaged() throws SchedulerException {
		SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
		sched = schedFact.getScheduler();
		sched.start();
		init(MongoManaged.getEvents());
	}

	public void start() throws Exception {
		
	}

	public void init(JacksonDBCollection<RolloEvent, String> events) {
		Iterator<RolloEvent> it = events.find().iterator();
		while (it.hasNext()) {
			RolloEvent ev = it.next();
			JobDataMap map = new JobDataMap();
			map.put(RolloEvent.KEY_EVENT_TYPE, ev.getEventType());
			map.put(RolloEvent.KEY_MOTOR, ev.getMotor().getId());

			String cronTrigger = "";
			for (char c : ev.getTrigger()) {
				cronTrigger += " " + c;
			}
			cronTrigger.trim();

			JobDetail jobDetail = JobBuilder
					.newJob(RolloJob.class)
					.withIdentity(ev.getId() + RolloEvent.JOB_SUFFIX,
							ev.getEventType().name()).setJobData(map).build();

			Trigger trigger = TriggerBuilder
					.newTrigger()
					.withIdentity(ev.getId() + RolloEvent.TRIGGER_SUFFIX,

					ev.getEventType().name())
					.withSchedule(CronScheduleBuilder.cronSchedule(cronTrigger))
					.build();
			try {
				sched.scheduleJob(jobDetail, trigger);
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void stop() throws Exception {
		sched.shutdown();
	}

}
